﻿// <copyright file="Eval.cs" company="Microsoft Corporation">
// Copyright (c) 2009 Microsoft Corporation All Rights Reserved
// </copyright>
// <author>Michael S. Scherotter</author>
// <email>mischero@microsoft.com</email>
// <date>2008-10-04</date>
// <summary>HTML eval() extension function</summary>

namespace Synergist
{
    using System;
    using System.Collections.Generic;
    using System.Windows.Browser;

    /// <summary>
    /// HTML Extension functions
    /// </summary>
    public static class HtmlEvaluator
    {
        /// <summary>
        /// The Dictionary cache
        /// </summary>
        private static Dictionary<string, string> dictionary = new Dictionary<string, string>();

        /// <summary>
        /// Evaluate the string and return it as a string on the HTML Window
        /// </summary>
        /// <param name="text">the string to evaluate - should be a JavaScript constant</param>
        /// <returns>the equivalent of JavaScript eval()</returns>
        /// <exception cref="ArgumentException">if text is evaluated to "" or null </exception>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Eval", Justification = "Mirroring OpenSocial API.")]
        public static string Eval(this string text)
        {
            lock (dictionary)
            {
                if (dictionary.ContainsKey(text))
                {
                    return dictionary[text];
                }

                var value = HtmlPage.Window.Eval(text) as string;

                if (string.IsNullOrEmpty(value))
                {
                    throw new ArgumentException(string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0} was not defined on the HTML Page.", text), "text");
                }

                dictionary[text] = value;

                return value;
            }
        }
    }
}
